package com.example.wm.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.wm.common.Result;
import com.example.wm.common.ResultData;
import com.example.wm.entity.Complaints;
import com.example.wm.entity.EmployeeManagement;
import com.example.wm.entity.Summary;


import com.example.wm.mapper.EmployedManageMapper;
import com.example.wm.mapper.SummaryMapper;
import com.example.wm.service.EmployedManageService;
import com.example.wm.service.SummaryService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController

@RequestMapping("/summary")
//总结
public class SummaryController {
    @Resource
    private SummaryService summaryService;
    @Resource
    private SummaryMapper summaryMapper;
    @Value("${reggie.url}")
    private  String url;
    @Value("${smbm.appsecret}")
    private String appsecreted;
    @Value("${smbm.appId}")
    private String appid;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private EmployedManageService employedManageService;
    @Resource
    private EmployedManageMapper employedManageMapper;
    @Transactional
    @PostMapping("/save")
    public Result SummarySave(@RequestBody Summary summary) {
        Set keys=redisTemplate.keys("summary*");
        redisTemplate.delete(keys);
        //时间
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        String time = formatter.format(date);
        summary.setTime(time);
        summaryService.save(summary);
        return ResultData.success("操作成功",1);
    }
    @Transactional
    @GetMapping ("/screate")
    //openid
    public Result screat( @RequestParam("code") String code){
        System.out.println(code+":code");
        // 获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //响应模型
        CloseableHttpResponse response = null;
        String openid = null;
        String newAccessTockenUrl="https://api.weixin.qq.com/sns/jscode2session?appid=wxba6a21693d6b5a99&secret=836e5643d37955fbaa32894a8614c60e&js_code="+code+"&grant_type=authorization_code";
        try {
            //创建get请求
            HttpGet httpGet = new HttpGet(newAccessTockenUrl);
            response = httpClient.execute(httpGet);
            //获取响应实体
            HttpEntity responseEntity = response.getEntity();
            String resultDemo = EntityUtils.toString(responseEntity);
            //转换成对象，好把需要的字段对应的值拿出来
            JSONObject jsonObject = JSONObject.parseObject(resultDemo);
            System.out.println("12122121"+jsonObject);
            openid= jsonObject.getString("openid");
//            return  ResultData.success("操作成功",openid);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  ResultData.success("操作成功",openid);
    }
    @Transactional
    @GetMapping ("/screateNewapp")
    //openid
    public Result screateNewapp( @RequestParam("code") String code){
        System.out.println(code+":code");
        // 获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //响应模型
        CloseableHttpResponse response = null;
        String openid = null;
        String newAccessTockenUrl="https://api.weixin.qq.com/sns/jscode2session?appid=wxff7ee9494b09e7e6&secret=eeb8f16926dc90deec33ce5a95486209&js_code="+code+"&grant_type=authorization_code";
        try {
            //创建get请求
            HttpGet httpGet = new HttpGet(newAccessTockenUrl);
            response = httpClient.execute(httpGet);
            //获取响应实体
            HttpEntity responseEntity = response.getEntity();
            String resultDemo = EntityUtils.toString(responseEntity);
            //转换成对象，好把需要的字段对应的值拿出来
            JSONObject jsonObject = JSONObject.parseObject(resultDemo);
            System.out.println("12122121"+jsonObject);
            openid= jsonObject.getString("openid");
//            return  ResultData.success("操作成功",openid);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  ResultData.success("操作成功",openid);
    }
    @Transactional
    @PostMapping("/findname")
    //查询
    public  Result Summaryfind(@RequestBody JSONObject jsonObject){
        // 接收传入数据
        String name = jsonObject.getString("name");
        String strDate=jsonObject.getString("strDate");
        if (name == null) {
            return ResultData.error(-1,"请检查参数是否正确");
        }
        // 创建查询构造器
        LambdaQueryWrapper<Summary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(Summary::getName,name);
        queryWrapper.eq(Summary::getState,"0");
        queryWrapper.between(Summary::getTime,strDate+"-01",strDate+"-31");
        // 调用mapper查询数据
        List<Summary> list = summaryMapper.selectList(queryWrapper);
        return ResultData.success("操作成功",list);
    }

 

    @PostMapping("/findAll_towe")
    public  Result SummaryfindAlltowe(@RequestBody JSONObject jsonObject){
        // 创建查询构造器
        LambdaQueryWrapper<Summary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Summary::getTime);
        queryWrapper.eq(Summary::getState,"0");

        // 调用mapper查询数据
        List<Summary> list = summaryMapper.selectList(queryWrapper);
        return ResultData.success("操作成功",list);
    }
    @Transactional
    @PostMapping("/token")
    public  Result Summarytoken() {
        String accessToken = null;
        String newAccessTockenUrl =url;
        // 获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //响应模型
        CloseableHttpResponse response = null;
        try {
            //创建get请求
            HttpGet httpGet = new HttpGet(newAccessTockenUrl);
            response = httpClient.execute(httpGet);
            //获取响应实体
            HttpEntity responseEntity = response.getEntity();
            String resultDemo = EntityUtils.toString(responseEntity);
            //转换成对象，好把需要的字段对应的值拿出来
            JSONObject jsonObject = JSONObject.parseObject(resultDemo);
            accessToken= jsonObject.getString("access_token");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultData.success(accessToken);



    }

    //根据id删除 撤回 state :0 1
    @PostMapping("/deletesummary")
    public Result<String> deletesummary(@RequestBody Summary summary){
        Set keys=redisTemplate.keys("summary*");
        redisTemplate.delete(keys);
//        summaryService.removeById(summary.getId());
        summaryService.updateById(summary);
        return  ResultData.success("删除成功");
    }
    //评分 1-5
    @PostMapping("/pf_summary")
    public Result<String> pf_summary(@RequestBody Summary summary){
        Set keys=redisTemplate.keys("summary*");
        redisTemplate.delete(keys);
//        summaryService.removeById(summary.getId());
        summaryService.updateById(summary);
        return  ResultData.success("修改成功");
    }
    //查找评分优秀的 4>
    @PostMapping("/pf_summary_good")
    public Result<List> pf_summary_good(@RequestBody JSONObject jsonObject ){
//        summaryService.removeById(summary.getId());
        String strDate = jsonObject.getString("strDate");
        LambdaQueryWrapper<Summary> lq=new LambdaQueryWrapper<>();
        lq.between(Summary::getTime,strDate+"-01",strDate+"-31");
        lq.ge(Summary::getStar,"4");
        List<Summary> list=summaryService.list(lq);
        return  ResultData.success(list);
    }
    //月报没有提交的
    @PostMapping("/Summery_notpush")
    public Result<List>  Summery_notpush(@RequestBody JSONObject jsonObject){
        String strDate = jsonObject.getString("strDate");

//        Date d1=new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
//        String strDate=sdf.format(d1);
//        log.info(strDate);
        LambdaQueryWrapper<Summary> lq=new LambdaQueryWrapper<>();
        lq.between(Summary::getTime,strDate+"-01",strDate+"-31");
        List<Summary> list=summaryMapper.selectList(lq);

        LambdaQueryWrapper<EmployeeManagement> lq2=new LambdaQueryWrapper<>();
        lq2.ne(EmployeeManagement::getLoginname,"林平康");
        lq2.ne(EmployeeManagement::getLoginname,"林天福");
        List<EmployeeManagement> list2=employedManageMapper.selectList(lq2);
        ArrayList<String> arr = new ArrayList<String> ();
        ArrayList<String> arr2 = new ArrayList<String> ();
        ArrayList<String> arr3 = new ArrayList<String> ();
        ArrayList<String> arr4 = new ArrayList<String> ();
        ArrayList<List> arr5= new ArrayList<List> ();


            for ( EmployeeManagement y:list2){
               arr.add(y.getLoginname());

        }
            for (Summary s:list){
                arr2.add(s.getName());


            }
        System.out.println(arr2);
        System.out.println(arr);

        for(int i = 0; i < arr.size(); i++){
              if(arr2.contains(arr.get(i))){
                  System.out.println(arr.get(i));
                  arr4.add(arr.get(i));
              }else {
                  arr3.add(arr.get(i));
              }
        }
        arr5.add(Collections.singletonList("nohavetj"));
        arr5.add(arr3);
        arr5.add(Collections.singletonList("havetj"));
        arr5.add(arr4);
        System.out.println("arr5"+arr5);

        return ResultData.success(arr5);
    }

}
